<template>
  <div class="container project-plan-wrapper">
    <a-spin :spinning='showTable' class='main-table'>
      <div id='btn-content' class="btn-content flex-center">
        <div class="btn-box flex-center">
          <a-button type="primary" @click='saveData(false)' v-if='userPerssion || isEditor'>{{$t('projectPlan.save')}}</a-button>
          <a-button @click="setExpandedRowKeys">{{expandTree ? $t('projectPlan.open') : $t('projectPlan.stowProjectPlan')}}</a-button>
          <a-button @click="urgedTaskHandle" v-if='userPerssion'>{{$t('projectPlan.urge')}}</a-button>
          <a-button @click="autoPublishBtn" v-if='userPerssion'>{{$t('projectPlan.autoPublishSettings')}}</a-button>
          <!--  :trigger="['click']"
              <a-menu-item key="autoPublishVisible">自动设置发布</a-menu-item> -->
          <a-dropdown v-if='userPerssion'>
            <a-button class="style-dropdown-button">
              {{$t('projectPlan.more')}} <a-icon type="dash" />
            </a-button>
            <a-menu slot="overlay" @click="handleMenuClick" class="style-dropdown-menu">
              <!-- <a-menu-item key="downPlanTemplate">下载计划模板</a-menu-item> -->
              <a-menu-item key="imporaOfflineTemplateVisible"> {{$t('projectPlan.offTemplateImport')}}</a-menu-item>
              <a-menu-item key="importProjectPlanVisible">{{$t('projectPlan.importExistPlan')}}</a-menu-item>
              <a-menu-item key="exportBtn">{{$t('projectPlan.exportPlan')}}</a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
        <div class="btn-box flex-center">
          <a-button v-if='userPerssion' @click="dialogVisible('deliverablesVisible')">{{$t('projectPlan.summaryDeliverables')}}</a-button>
          <a-input-search placeholder="请输入搜索关键词" style="width: 224px" @search="onSearch" />
          <a-icon type="google" class='icon-gantt' @click='clickGantt'/>
        </div>
      </div>
      <main-table ref="ref_table" :tableName='tableName' :projectTeamUsers="projectTeamUsers" :resourceOptsKey="resourceOptsKey" 
        @onSelectChange="onSelectChange" @tableUpdated='tableUpdatedHandler'/>
    </a-spin>
    <!-- 设置自动发布 -->
    <auto-publish :dialogVisible="autoPublishVisible" @ok="autoPublishOk" @cancel="autoPublishCancel"></auto-publish>
    <!-- 导入线下模板 -->
    <import-offline-template :dialogVisible="imporaOfflineTemplateVisible" @cancel="dialogVisible('imporaOfflineTemplateVisible')"  @ok="imporaOfflineTemplateSuccess"></import-offline-template>
    <!-- 导入已有项目计划 -->
    <import-project-plan v-if="importProjectPlanVisible" :dialogVisible="importProjectPlanVisible" @cancel="dialogVisible('importProjectPlanVisible')"  @ok="importProjectPlanSuccess"></import-project-plan>
    <!-- 交付物汇总 -->
    <deliverables-summary v-if="deliverablesVisible && data && data[0]" :oid="data[0].oid" :dialogVisible="deliverablesVisible" @cancel="dialogVisible('deliverablesVisible')"  @ok="dialogVisible('deliverablesVisible')"></deliverables-summary>
    <!-- 催办 -->
    <urged-task :dialogVisible="urgedTaskeVisible" :urgedTaskOid="urgedTaskOid" @cancel="dialogVisible('urgedTaskeVisible')"  @ok="urgedTaskSuccess"></urged-task>
  </div>  
</template>
<script>
import mainTable from '@/components/pubTable'
import importOfflineTemplate from './components/importOfflineTemplate'
import importProjectPlan from './components/importProjectPlan'
import urgedTask from './components/urgedTask'
import deliverablesSummary from './components/deliverablesSummary'
import globalSearch from "@/components/common/globalSearch"
import autoPublish from './components/autoPublish'
import { timeFormat } from '@/utils/util.js'
import { mapMutations, mapGetters } from 'vuex'
import { showColumnsAdapter } from './js/columnsAdapter.js'
import { downPlanTemplate }  from "@api/projectPlan";
import {
  getColumns,
  getShowColumns,
  getShowSource,
  getUserConfig,
  getKeyNodeName,
  saveUpdateInfo,
} from "@api/planComponent";
import { saveFile } from '@/utils/util'

import { planColumnsRes, planShowColumnsRes, planTableData, configUsers, keyNodes } from './js/mock.js'
import _ from 'lodash'
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
export default {
    name: 'ganttNeed',
    provide() {
      return {
        setMinMaxDate: this.setMinMaxDate,
        mathWorkTime: this.mathWorkTime,
        loadingTable: this.loadingTable,
        saveData: this.saveData
      }
    },
    components: { mainTable, globalSearch, importOfflineTemplate, importProjectPlan, deliverablesSummary, urgedTask, autoPublish },
    computed: {
      ...mapGetters({
        isLastChildNode: 'isLastChildNode',
        showSource: 'getPlanTable',
        isAddNode: 'isAddNode',
        getRowEditable: 'getRowEditable',
        getAllTable: 'getAllTable',
        getDependcyDate: 'getDependcyDate'
      }),
      userPerssion() {
        return this.$store.state.planTable.userEditable
      }
    },
    data() {
      return {
        workTimeOfDay: 24,
        dateFormat: 'YYYY-MM-DD',
        templateColumns: [],
        planId: '',
        defaultCols: [
          '健康状态',
          '任务状态',
          '名称',
          '四级汇总节点',
          '关键节点',
          '目标开始时间',
          '目标完成时间',
          '实际完成时间',
          '完成百分比',
          '交付物',
          '执行人',
          '审核人',
          '编辑者',
          '是否锁定',
          '锁定者',
        ],
        notSaveList: [
          'selected',
          'activityType',
          'show',
          'taskCode',
          'isFolder',
          'deliverable',
          'dependencies',
          'parentIds',
          'actualEndDate',
          'actualStartDate',
          'creator',
          'modifier',
          'notDeleteable',
          'thePersistInfo.createStamp',
          'thePersistInfo.modifyStamp'
        ],
        expandTree: false,
        searchData: [], //搜索数据
        data: [],
        tableName: '项目计划',
        reviewerReferenceOpts: [],
        activityTypeOpts: [],
        resourceOpts: [],
        resourceOptsKey: {},
        showTable: true,
        importProjectPlanVisible: false,
        imporaOfflineTemplateVisible: false,
        urgedTaskeVisible: false,
        commonParams: {
          userId: userinfo.loginName
        },
        deliverablesVisible: false,
        autoPublishVisible: false, // 自动发布设置参数
        projectTeamUsers: {}, //设置审核人，编辑者转换
        selectedRowKeys: [], // 表格选中数据
        urgedTaskOid: [], // 任务oid 催办
        projectId: '',
        isEditor: false,
        tempSaveSource: [],
        keyNodeOpertor: [
          'cn.com.sany.RDImprovementProject',         //研发能力提升项目   可以选择关键节点
          'cn.com.sany.ProcessImprovementProject'         //制造工艺提升项目
        ],
        autoSaveInterVal: null
      }
    },
    mounted() {
      const self = this;
      self.projectId = `OR:com.pisx.pmgt.project.PIProject:${sessionStorage.getItem('oid')}`
      self.getNetData();
      // self.autoSave();
    },
    methods: {
        ...mapMutations(['setDefaultColumns','setPlanTable','setRowOfPlanTable',
        'copyTableForCompare','setKeyNodeOpterable']),
        //其他页面加载表格
        loadingTable(flag) {
          this.showTable = flag
        },
        //当表格修改重新开始自动保存的计时
        tableUpdatedHandler() {
          // clearInterval(this.autoSaveInterVal)
          // this.autoSave();
        },
        //自动保存
        autoSave() {
          const self = this;
          self.autoSaveInterVal = setInterval(() => {
            const back = self.saveData(true)
            if (back.updateData.length > 0)
              self.saveData(false)
          },120000)
        },
        getNetData(delResource = false) {
          const self = this;
          // self.showTable = true
          /**hlu-edit */
          self.showTable = false
          self.$store.state.planTable.filterMap = new Map()
          self.$store.state.planTable.hasSelectData = []
          self.getTableColumns(delResource);   //得到表格列
          self.getTableSource();    //得到表格数据
          self.getConfig();       //得到配置项
          self.getKeyNodeName();    //得到关键节点名称
        },
        getKeyNodeName() {
            // getKeyNodeName({
            //     oid: this.projectId,
            // }).then(res => {
              let res = keyNodes
                this.$store.state.planTable.keyNodeNames = res.data.data
            // })
        },
        // 全局搜索
        onSearch(val, searchValue) {
          this.$refs.ref_table.onSearch(val)
        },
        clickGantt() {
          this.$refs.ref_table.showGanttView()
        },
        handleButtonClick(e) {
          console.log('click left button');
        },
        handleMenuClick(e) {
          if (e.key === 'downPlanTemplate') {
            let _ = this
            const params = {};
            params.userId = _.commonParams.userId;
            downPlanTemplate(params).then(res => {
              if (res && res.status === 200) {
                const blob = new Blob([res.data], {type: 'application/octet-stream'})
                saveFile(blob, '计划模板.xlsx')
              } else {
                this.$message.warn('导出异常')
              }
            })
          } else if (e.key === 'exportBtn') {
            this.exportBtn()
          } else if (e.key === 'imporaOfflineTemplateVisible') {
            // 线下模板导入
            if (this.data && this.data.length) {
              this.$confirm({
                cancelText:"否",
                okText:"是",
                content: h => <div>已有项目计划，是否覆盖？</div>,
                onOk: () => {
                  this.dialogVisible(e.key)
                }
              })
            } else {
              this.dialogVisible(e.key)
            }
          } else if (e.key === 'importProjectPlanVisible') {
            // 导入已有项目计划
            if (this.data && this.data.length) {
              this.$confirm({
                cancelText:"否",
                okText:"是",
                content: h => <div>已有项目计划，是否覆盖？</div>,
                onOk: () => {
                  this.dialogVisible(e.key)
                }
              })
            } else {
              this.dialogVisible(e.key)
            }
          }  else {
            this.dialogVisible(e.key)
          }
        },
        dialogVisible(key) {
          if (key === 'deliverablesVisible') {
            // 交付物汇总无数据时不弹框
            if (this.data && this.data.length) {
              this[key] = !this[key]
            } else {
              this.$message.info('暂无数据')
            }
          } else {
            this[key] = !this[key]
          }
        },
        autoPublishBtn() {
          this.autoPublishVisible = true
        },
        autoPublishOk() {
          this.autoPublishVisible = false
        },
        autoPublishCancel() {
          this.autoPublishVisible = false
        },
        exportBtn() {
          this.$refs.ref_table.exportBtn()
        },
        setResourceType(obj,data) {
          const self = this;
          self.$set(obj,'targetWorkQty',data.targetQty)
          self.$set(obj,'targetEquipQty',0)
          const reourceType = self.resourceOpts.find(item => item.value == data.resourceId)
          if (reourceType != undefined && reourceType.type != "labor") {
            self.$set(obj,'targetWorkQty',0)
            self.$set(obj,'targetEquipQty',data.targetQty)
          }
        },
        //保存数据
        saveData(backParams = false) {
          const self = this;
          const compareTable = self.$store.state.planTable.compareDefaultTable;
          let allTable = this.getAllTable();
          let addData = [],updateData = [],lineNumberData = []
          for(let index = 0,len1 = allTable.length; index < len1; index++){
            let item = allTable[index]
            const parentNode = allTable.find(temp0 => temp0.id == item.parentIds[item.parentIds.length - 1]);
            const brotherNodes = allTable.filter(temps => JSON.stringify(temps.parentIds) == JSON.stringify(item.parentIds))
            const parentTaskCode = parentNode != undefined ? parentNode.taskCode : item.taskCode
            const interIndex = brotherNodes.findIndex(temp1 => temp1.id == item.id)
            if (this.isAddNode(item.id)) {
              //新增的数据
              let add = {}
              for(let [key,value] of Object.entries(item)) {
                if (self.notSaveList.includes(key))
                  continue;
                if (key == 'predecessor' && value.predecessorOid != undefined) {
                  self.$set(add,'dependency',[{
                    dependencyId: value.dependencyId,
                    precedenceType: value.Type,
                    predecessorId: value.predecessorOid,
                    scheduleOffset: value.lag,
                    scheduleOffsetUnit: "DAYS",
                    successorId: value.successor
                  }])
                  continue;
                }
                if (key == 'targetStartDate' || key == 'targetEndDate') {
                  const tempDate = timeFormat(value,'YYYY-MM-DD')
                  self.$set(add,key,`${tempDate}T00:00:00.0 Z`)
                  continue;
                }
                if ((key == 'effort' || key == 'resource') && item.resource != undefined && item.resource.toString().length > 0) {
                  if(item.resource == 0 || item.resource == '') {
                    self.$set(add,'resourceAssignment', [])
                    continue;
                  }
                  let resourceAssignment = {
                    allocationPercentage: '100',
                    targetQty: item.effort.toString().length == 0 ? 0 : item.effort
                  }
                  resourceAssignment.resourceId = item.resource
                  self.$set(add,'resourceAssignment',[resourceAssignment])
                  //如果执行人是labor类型，设置targetWorkQty时间。否则设置targetEquipQty
                  self.setResourceType(add,resourceAssignment)
                  continue;
                }
                if (value != '')
                  self.$set(add,key,value)
              }
              add.lineNumber = index
              add.internalIndex = interIndex
              add.parentId = parentNode && parentNode.oid
              add.taskCode = `${parentTaskCode}.${interIndex + 1}`
              add.durationType = 'FixedDrtn'
              if (self.isLastChildNode(add)) {
                add.activityType = 'Task'
              }else {
                add.activityType = 'WBS'
              }
              addData.push(add)
            }else {
              //对已有数据的处理
              let compareItem = compareTable.find(compare => item.id == compare.id)
              let update = {}
              const isChildNode = self.isLastChildNode(item,false);
              if (compareItem.activityType != item.activityType) {
                update.activityType = isChildNode ? 'Task' : 'WBS'
              }
              //如果父节点层级发生变化，修改节点关系
              if (JSON.stringify(item.parentIds) != JSON.stringify(compareItem.parentIds)) {
                update.parentId = parentNode && parentNode.oid
              }
              for(let [key,value] of Object.entries(item)) {
                //notSaveList中的key不进行处理
                if (self.notSaveList.includes(key))
                  continue;
                //如果顺序发生改变，加入lineNumberData
                if (key == 'lineNumber' && index != item.lineNumber) {
                  update.lineNumber = index
                  lineNumberData.push({
                    taskId: item.taskId,
                    lineNumber: index
                  })
                  continue;
                }
                //如果层级内发生变化
                if (key == 'internalIndex' && item.internalIndex != interIndex) {
                  //设置同级节点中的位置
                  update.internalIndex = interIndex
                  update.taskCode = `${parentTaskCode}.${interIndex + 1}`
                  continue
                }
                //如果数据修改了
                if (JSON.stringify(value) != JSON.stringify(compareItem[key])) {
                  if (key == 'predecessor') {
                    self.$set(update,'dependency',[{
                      dependencyId: value.dependencyId,
                      precedenceType: value.Type,
                      predecessorId: value.predecessorOid,
                      scheduleOffset: value.lag,
                      scheduleOffsetUnit: "DAYS",
                      successorId: value.successor
                    }])
                    continue;
                  }
                  if (key == 'targetStartDate' || key == 'targetEndDate') {
                    const tempDate = timeFormat(value,'YYYY-MM-DD')
                    self.$set(update,key,`${tempDate}T00:00:00.0 Z`)
                    continue;
                  }
                  //如果工时和执行人修改了且必须有执行人，进行特殊处理
                  console.log(item.resource)
                  if ((key == 'effort' || key == 'resource') && item.resource != undefined) {
                    if(item.resource == 0 || item.resource == '') {
                      self.$set(update,'resourceAssignment', [])
                      continue;
                    }
                    let resourceAssignment = {
                      allocationPercentage: '100',
                      targetQty: item.effort.toString().length == 0 ? 0 : item.effort
                    }
                    if (item.assignmentId != undefined && item.assignmentId.toString().length > 0) {
                      resourceAssignment.assignmentId = `PIProjectManager.model.Assignment-${item.assignmentId}`
                    }
                    if (item.roleId != undefined && item.roleId.toString().length > 0) {
                      resourceAssignment.roleId = item.roleId
                    }
                    resourceAssignment.resourceId = item.resource
                    self.$set(update,'resourceAssignment',[resourceAssignment])
                    //如果执行人是labor类型，设置targetWorkQty时间。否则设置targetEquipQty
                    self.setResourceType(update,resourceAssignment)
                    continue;
                  }
                  self.$set(update,key,value)
                }
              }
              //如果当前行发生了修改，则加入updateData
              if (Object.entries(update).length > 0) {
                update.taskId = item.oid
                updateData.push(update)
              }
            }
          }
          let temp = {
            planId: this.planId.substring(this.planId.lastIndexOf(':') + 1,this.planId.length),
            updateData: updateData,
            addData: addData,
            lineNumberData: lineNumberData
          }
          //当剪切时，需要将剪切掉的行一起删除
          let delIds = []
          self.$store.state.planTable.shearId.forEach(id => {
            delIds.push({
              taskOid: id
            })
          })
          let deleteActivityDatas = {
            deleteLineNumbers: delIds,
            lineNumberData: []
          }
          if (backParams) {
            return temp
          }else {
            self.showTable = true
            // saveUpdateInfo({
            //   oid: this.planId,
            //   saveActivityDatas: JSON.stringify(temp),
            //   deleteActivityDatas: delIds.length == 0 ? '' : JSON.stringify(deleteActivityDatas)
            // }).then(res => {
            //   if(res.data.status == 'error') {
            //     self.$message.error(res.data.info)
            //   }else {
            //     self.replaceNowTable(res.data.returnData)
                self.$message.success('保存成功')
            //   }
            //   self.showTable = false
            // })
          }
        },
        //将保存后的数据替换原有的
        replaceNowTable(data) {
          const self = this;
          let rowIdMap = new Map()
          let allTable = this.getAllTable();
          for(let index = 0,len = data.length; index < len; index++) {
         // for(let index = 0,len2 = data.length; index < len2; index++) {
            let item = data[index]
            //得到返回数据的对应行
            const currentIndex =  allTable.findIndex(temp => temp.id == (item.rowId.length > 0 ? item.rowId : item.id))
            let currentRow = allTable[currentIndex]
            if (item.rowId.length > 0) {
              //设置rowid对应的正确id
              rowIdMap.set(item.rowId,item.id)
              //新增数据替换
              self.isLastChildNode(currentRow,false) ? currentRow.activityType = 'Task' : currentRow.activityType = 'WBS'
              currentRow.id = item.id + '';
              currentRow.oid = item.taskOid;
              currentRow.taskId = item.taskId;
              currentRow.rowId = '';
            }
            if (currentRow != undefined) {
              currentRow.dependencies = [item.parentId.toString()]
              //添加条件避免修改顶级节点
              if (currentRow.parentIds.length > 0) {
                //替换parentIds中的rowid
                for (let [key, value] of rowIdMap) {
                  currentRow.parentIds = currentRow.parentIds.join(',').replace(key,value.toString()).split(',')
                }
              }
              //如果有前置任务设置任务id
              if (item.dependency != undefined && item.dependency.length > 0 && item.dependency[0].dependencyOid != undefined)
                currentRow.predecessor.dependencyId = item.dependency[0].dependencyOid
              currentRow.lineNumber = item.lineNumber
              currentRow.internalIndex = item.internalIndex
              currentRow.taskCode = item.taskCode
              //如果重写的数据在compareDefaultTable中有映射，则替换映射数据。负责将数据插入到compareDefaultTable
              //写入compareDefaultTable用于保存后去掉页面上的标识图标
              self.replaceTable(self.$store.state.planTable.compareDefaultTable,JSON.parse(JSON.stringify(currentRow)),currentIndex)
              //allPlanTable同理
              self.replaceTable(self.$store.state.planTable.allPlanTable,JSON.parse(JSON.stringify(currentRow)),currentIndex)
              //对现有的展示数据进行修改
              if (self.$store.state.planTable.planTable[currentIndex] != undefined)
                self.$set(self.$store.state.planTable.planTable,currentIndex,JSON.parse(JSON.stringify(currentRow)))
            }
          }
        },
        replaceTable(table,currentRow,currentIndex) {
          const index = table.findIndex(data => data.id == currentRow.id)
          if (index != -1) {
            this.$set(table,index,currentRow)
          }else {
            table.splice(currentIndex,0,currentRow)
          }
        },
        // 催办
        urgedTaskHandle() {
          if (!this.selectedRowKeys.length) {
            this.$message.info('请选择催办任务')
          } else {
            let plannableStatusData = this.$store.state.planTable.allConfig.enumerateLocalList.plannableStatus
            let check = true
            this.selectedRowKeys.forEach(item => {
              if (item.activityType === 'WBS') {
                this.$message.error(item.name + ', WBS节点不能催办')
                check = false
                return false
              } else if (plannableStatusData[item.plannableStatus] === '已完成') {
                this.$message.error(item.name + ', 已完成，不能催办')
                check = false
                return false
              } else if (plannableStatusData[item.plannableStatus] === '未发布') {
                this.$message.error(item.name + ', 未发布，不能催办')
                check = false
                return false
              } else if (plannableStatusData[item.plannableStatus] === '暂停') {
                this.$message.error(item.name + ', 暂停，不能催办')
                check = false
                return false
              } else if (plannableStatusData[item.plannableStatus] === '待审核') {
                this.$message.error(item.name + ', 待审核，不能催办')
                check = false
                return false
              }
            })
            if(check) {
              this.urgedTaskOid = this.selectedRowKeys.map(item => item.oid)
              this.urgedTaskeVisible = true
            }
          }
        },
        // 线下模板导入
        imporaOfflineTemplateSuccess(success) {
          if (success) {
            this.getNetData()
          }
          this.imporaOfflineTemplateVisible = false
        },
        // 已有项目计划导入
        importProjectPlanSuccess(success) {
          if (success) {
            this.getNetData(true)
          }
          this.importProjectPlanVisible = false
        },
        urgedTaskSuccess() {
          this.urgedTaskeVisible = false
          this.selectedRowKeys.forEach(ele => {
            ele.selected = false;
            this.setRowOfPlanTable(ele)
          })
          this.selectedRowKeys = []
        },
        onSelectChange(selectedRowKeys) {
          this.selectedRowKeys = selectedRowKeys;
        },
        setExpandedRowKeys() {
          this.$refs.ref_table.setExpandedRowKeys(this.expandTree)
          this.expandTree = !this.expandTree
        },
        getConfig() {
            const self = this;
            let obj = {
                "pi-pmgt-project": [
                    "createPlan"
                ],
                "pi-pmgt-act": [
                    "deleteActivityAccess",
                    "updateActivityAccess",
                    "updatePredecessorAccess",
                    "updateProjectCalendars",
                    "saveActivityAccess"
                ]
            }
            // getUserConfig({
            //     oid: this.projectId,
            //     checkConfigJson: JSON.stringify(obj),
            // }).then(res => {
              let res = configUsers
                self.$store.state.planTable.allConfig = res.data.returnData
                self.getUserPerssion(res.data.returnData)
                //设置审核人，编辑者 选择数据
                self.reviewerReferenceOpts = self.setKeyValOpts(self.reviewerReferenceOpts,
                    Object.entries(res.data.returnData.projectTeamUsers))
                self.projectTeamUsers = res.data.returnData.projectTeamUsers
                //设置活动类别选择数据
                self.activityTypeOpts = self.setKeyValOpts(self.activityTypeOpts,
                    Object.entries(res.data.returnData.enumerateLocalList.activityType))
                //设置关键节点操作权限
                self.setKeyNodeOpterable(self.keyNodeOpertor.includes(res.data.returnData.projectType))
                self.setColOpts()
            // })
        },
        //得到用户权限
        getUserPerssion(data) {
          let pers = []
          pers.push(...this.getAllowPerssion(data.projectAdmin))
          pers.push(...this.getAllowPerssion(data.projectEngineer))
          pers.push(...this.getAllowPerssion(data.projectManager))
          this.$store.state.planTable.userEditable = pers.includes(this.$store.state.planTable.allConfig.currentUser) || data.isAdmin;
        },
        //可行的权限
        getAllowPerssion(obj) {
          let perssions = []
          for(let [key] of Object.entries(obj)){
            perssions.push(key)
          }
          return perssions
        },
        setKeyValOpts(list,entries) {
            list = []
            for(let [key,value] of entries) {
                list.push({
                    value: key,
                    label: value
                })
            }
            return list;
        },
        //得到列表列
        getTableColumns(delResource) {
            const self = this;
            let res = planColumnsRes
            let showRes = planShowColumnsRes
            // let requests = [
            //     getShowColumns({
            //         tableName: self.tableName
            //     }),
            //     getColumns()
            // ]
            // Promise.all(requests).then(res => {
                // let show = res[0].data
                // let all = res[1].data.data
                /**hlu-edit */
                let show = showRes
                let all = res.data
                if (delResource)
                  all.splice(all.findIndex(data => data.name == "resource"),1)
                this.$store.state.planTable.showColOfHeaderConfig = show.labelList.length == 0 ? self.defaultCols : show.labelList.split(',')
                let allCols = _.clone(all);
                self.initAllColumns(allCols)
            // })
        },
        //初始化列表列
        initAllColumns(columns) {
            // let storeShowColumns = []
            columns.forEach(item => {
                let target = showColumnsAdapter.find(adapter => adapter.dataIndex == item.name)
                if(target != undefined) {
                    if(target.noTitle == undefined || !target.noTitle)
                        target.title = item.displayName
                    Object.assign(item,target)
                }
            })
            this.templateColumns = columns
            console.log(this.templateColumns, 697);
            this.$store.state.planTable.noShowColOfHeaderConfig = _.clone(columns)
            this.setColOpts()
        },
        //得到列表数据
        getTableSource() {
            this.$store.state.planTable.planTable = []
            this.$store.state.planTable.allPlanTable = []
            this.$store.state.planTable.compareDefaultTable = []
            // getShowSource({
            //     oid: sessionStorage.getItem('oid'),
            //     columnNames: ""
            // }).then(res => {
              let res = planTableData
              if (res.data.success || res.data.success == 'success') {
                const planId = res.data.tasks[0].oid
                sessionStorage.setItem('PIPlanId',planId)
                this.planId = planId;
                this.$store.state.planTable.assignments = res.data.assignments
                this.tempSaveSource = res.data.tasks
                this.resourceOpts = []
                this.resourceOptsKey = {}
                res.data.resources.forEach(item => {
                  this.resourceOpts.push({
                    value: item.resourceId,
                    label: item.resourceName,
                    type: item.resourceType
                  })
                  this.resourceOptsKey[item.resourceId] = item.resourceName
                })
                this.setColOpts()
              }else {
                this.$message.error('没有项目任务.')
                this.showTable = false
              }
            // })
        },
        //处理表格数据
        initTableData() {
          let back = this.tempSaveSource;
          for (let index = 0, len3 = back.length; index < len3; index++) {
            let target = back[index]
            if (target.deliverable == undefined) {
              target.deliverable = []
            }
            
            //设置每一行的编辑权限并给头部按钮设置权限
            target.actionPerssion = this.getRowEditable(target,back)
            if (target.actionPerssion)
              this.isEditor = true;
            //给每个子节点设置工时
            if (this.isLastChildNode(target))
              this.mathWorkTime(target,target.targetStartDate,target.targetEndDate,back);
          }
          //parentIds字符串用于判断是否是兄弟节点
          let strParentIds = ''
          for (let index = 0, len4 = back.length; index < len4; index++) {
            let target = back[index]
            //只需给让一个同级节点设置即可
            if (this.isLastChildNode(target) && JSON.stringify(target.parentIds) != strParentIds) {
              strParentIds = JSON.stringify(target.parentIds)
              //设置父节点的最早开始时间和最晚结束时间
              this.setMinMaxDate(target,back,true)
            }
          }
          this.data = JSON.parse(JSON.stringify(back))
          this.$store.state.planTable.loadNodeId = null
          this.$store.state.planTable.allPlanTable = JSON.parse(JSON.stringify(back))
          this.$store.state.planTable.compareDefaultTable = JSON.parse(JSON.stringify(back))
          this.setPlanTable()
        },
        //设置执行人 审核人的选择数据
        setColOpts() {
          if (this.templateColumns.length > 0 && this.resourceOpts.length > 0 && this.reviewerReferenceOpts.length > 0) {
            this.initTableData()
            this.templateColumns.find(item => item.dataIndex == 'reviewerReference').editInfo = _.clone(this.reviewerReferenceOpts)
            this.templateColumns.find(item => item.dataIndex == 'editorReference').editInfo = _.clone(this.reviewerReferenceOpts)
            this.templateColumns.find(item => item.dataIndex == 'activityType').editInfo = _.clone(this.activityTypeOpts)
            if (this.templateColumns.find(item => item.dataIndex == 'resource') != undefined)
              this.templateColumns.find(item => item.dataIndex == 'resource').editInfo = _.clone(this.resourceOpts)
            //设置任务状态筛选下拉数据
            let planStatus = []
            for(let [key,value] of Object.entries(this.$store.state.planTable.allConfig.enumerateLocalList.plannableStatus)) {
              planStatus.push({
                label: value,
                value: key
              })
            }
            this.templateColumns.find(item => item.dataIndex == 'plannableStatus').editInfo = planStatus
            this.setDefaultColumns(this.templateColumns)
            this.showTable = false
          }
        },//设置每个父节点的最大结束时间和最小开始时间
        setMinMaxDate(lastChild,mainData,initFlag,predecessorFlag = false) {
          if(lastChild.parentIds.length == 0 || lastChild.parentIds[0] == '') 
              return
          //父节点id
          const parentNodeId = lastChild.parentIds[lastChild.parentIds.length - 1];
          let tempStart = '',tempEnd = ''
          //父节点
          let parentNode = mainData.find(item => item.id == parentNodeId)
          if (initFlag) {
            //目标节点的兄弟节点
            const brotherNodes = mainData.filter(item => item.parentIds[lastChild.parentIds.length - 1] == parentNodeId)
            //找到兄弟节点中最晚的结束时间和最早的开始时间
            brotherNodes.forEach(ele => {
              let eleStart =  new Date(ele.targetStartDate)
              tempStart = tempStart == '' ? timeFormat(ele.targetStartDate,this.dateFormat) : 
                new Date(tempStart).getTime() < eleStart.getTime() ? tempStart : timeFormat(eleStart,this.dateFormat)
              let eleSEnd =  new Date(ele.targetEndDate)
              tempEnd = tempEnd == '' ? timeFormat(ele.targetEndDate,this.dateFormat) : 
                new Date(tempEnd).getTime() > eleSEnd.getTime() ? tempEnd : timeFormat(eleSEnd,this.dateFormat)
            })
          }else {
            //修改单个数据时直接与父节点对比
            tempStart = new Date(parentNode.targetStartDate).getTime() < new Date(lastChild.targetStartDate).getTime() ? 
              timeFormat(parentNode.targetStartDate,this.dateFormat) : timeFormat(lastChild.targetStartDate,this.dateFormat)
            tempEnd = new Date(parentNode.targetEndDate).getTime() > new Date(lastChild.targetEndDate).getTime() ? 
              timeFormat(parentNode.targetEndDate,this.dateFormat) : timeFormat(lastChild.targetEndDate,this.dateFormat)
          }
          //重新设置父节点的开始时间和结束时间
          parentNode.targetStartDate = tempStart
          parentNode.targetEndDate = tempEnd
          this.mathWorkTime(parentNode,parentNode.targetStartDate,parentNode.targetEndDate,mainData);
          this.setRowOfPlanTable(parentNode)
          if (predecessorFlag)
            this.setPredecessorDate(lastChild)
          //如果父节点上还有父级节点则继续调用函数
          if(parentNode.parentIds.length > 0) 
            this.setMinMaxDate(parentNode,mainData,initFlag)
        },
        //设置前置任务时间
        setPredecessorDate(node) {
          //所有前置任务为lastChild的任务
          let currentRows = this.getAllTable().filter(item => item.predecessor.predecessor != undefined && item.predecessor.predecessor == node.id)
          //给这些任务重新设置时间
          currentRows.forEach(currentRow => {
            //任务的前置任务不能是父任务 且状态为未发布
            if (!currentRow.parentIds.includes(node.id) && currentRow.id != node.id &&
              currentRow.plannableStatus == "SCHEDULED") {
              let delay = (currentRow.predecessor.lag && currentRow.predecessor.lag != undefined && currentRow.predecessor.lag != '') ? 
                parseInt(currentRow.predecessor.lag) : 0
              const dateBack = this.getDependcyDate(node,currentRow['targetDuration.millis'],delay,currentRow.predecessor.Type)
              currentRow.targetStartDate = timeFormat(dateBack.start,this.dateFormat)
              currentRow.targetEndDate = timeFormat(dateBack.end,this.dateFormat)
              this.setRowOfPlanTable(currentRow)
              this.setMinMaxDate(currentRow,this.getAllTable(),true,true)
            }
          })
        },
        //计算工时和工期
        mathWorkTime(target,startDate,endDate,allTable = null) {
          const start = new Date(timeFormat(startDate,this.dateFormat))
          const end = new Date(timeFormat(endDate,this.dateFormat))
          
          target.targetStartDate = timeFormat(startDate,this.dateFormat)
          target.targetEndDate = timeFormat(endDate,this.dateFormat)
          //如果是子节点直接设置工时 工期
          if (this.isLastChildNode(target)) {
            const days = ((end.getTime() - start.getTime()) / (1000*60*60*24) + 1)
            target["targetDuration.millis"] = days
            target.effort = days * this.workTimeOfDay
          }else {
            //所有表格数据
            allTable = allTable ? allTable : this.getAllTable()
            //如果是父节点，则统计下一级节点的时间并赋值
            let childNodes =  allTable.filter(ele => ele.parentIds[ele.parentIds.length - 1] == target.id)
            let days = 0
            childNodes.forEach(item => {
              days += parseInt(item["targetDuration.millis"])
            })
            target["targetDuration.millis"] = days
            target.effort = days * this.workTimeOfDay
          }
        },
    },
    
}
</script>
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .container {
    height: calc(100% - 36px);
    width: 100%;
    background: #fff;
    overflow-y: scroll;
  }
  .main-table .ant-spin-container {
    height: 100%
  }
</style>
<style scoped lang="less">
  @import "./index.less";
  .icon-gantt {
    size: 20px;
    font-size: 20px;
    cursor: pointer;
    margin-left: 10px;
  }
</style>